package com.coolingme.Object;

import java.io.*;

/**
 * 对象流 基础用法
 *
 * @author wangyue
 * @date 2019/4/3 14:14
 */
public class ObjectStream {

    public static void main(String[] args) {
        File file = new File("D://Java//IntelliJIDEA//workspace//java-learn//IO//file//fileBuffered//person.txt");//文件对象

        String path = "D://Java//IntelliJIDEA//workspace//java-learn//IO//file//fileBuffered//person.txt";//目标路径

        Person p = new Person("wangyue", 23); // 新建一个对象

        objectOutput(path, p);

        Person person = (Person) objectInput(file);
        System.out.println(person);
        person.hello();
    }

    /**
     * 将对象写到文件中
     *
     * @param path   保存的路径
     * @param object 需要保存的对象
     */
    public static void objectOutput(String path, Object object) {
        FileOutputStream out = null;
        ObjectOutputStream bout = null;
        try {
            out = new FileOutputStream(path);//低级流
            bout = new ObjectOutputStream(out);//高级流以低级流为基础
            bout.writeObject(object);//将对象写入文件中
            bout.flush();//刷新
            System.out.println("对象写入成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
        }
    }

    /**
     * 读取文件中的对象
     *
     * @param file 文件对象
     */
    public static Object objectInput(File file) {
        Object object = null;
        FileInputStream in = null;
        ObjectInputStream bin = null;
        try {
            in = new FileInputStream(file);
            bin = new ObjectInputStream(in);
            object = bin.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
        }
        return object;
    }
}

